package com.bac.rentmap.ad.flat.jdo;

import java.util.Random;

import javax.jdo.PersistenceManager;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.SecureFlatAdNotFoundException;
import com.google.appengine.api.memcache.MemcacheService;

public class CachingJdoFlatAdDao implements JdoFlatAdDao {
    private JdoFlatAdDao jdoFlatAdDao;
    private MemcacheService cache;
    private double cachePutProbability = 1;
    private Random random = new Random();

    public void setJdoFlatAdDao(JdoFlatAdDao jdoFlatAdDao) {
        this.jdoFlatAdDao = jdoFlatAdDao;
    }

    public void setCache(MemcacheService cache) {
        this.cache = cache;
    }

    public void setCachePutProbability(double cachePutProbability) {
        this.cachePutProbability = cachePutProbability;
    }

    public FlatAd find(String street, Integer building, String phone,
            PersistenceManager persistenceManager) {
        return jdoFlatAdDao.find(street, building, phone, persistenceManager);
    }

    public FlatAd get(Long flatAdId) {
        FlatAd res = (FlatAd) cache.get(flatAdId);
        if(res != null)
            return res;
        res = jdoFlatAdDao.get(flatAdId);
        if(canPutIntoCache()){
            cache.put(flatAdId, res);
        }
        return res;

    }

    private boolean canPutIntoCache(){
        return random.nextDouble() <= cachePutProbability;
    }

    public FlatAd getBySecureId(String secureId) {
        return jdoFlatAdDao.getBySecureId(secureId);
    }

    public FlatAd loadBySecureId(String secureId,
            PersistenceManager persistenceManager)
            throws SecureFlatAdNotFoundException {
        return jdoFlatAdDao.loadBySecureId(secureId, persistenceManager);
    }

    public FlatAd loadBySecureId(String secureId)
            throws SecureFlatAdNotFoundException {
        return jdoFlatAdDao.loadBySecureId(secureId);
    }

    public Long deleteBySecureId(String secureId) {
        Long flatAdId = jdoFlatAdDao.deleteBySecureId(secureId);
        if(flatAdId != null){
            cache.delete(flatAdId);
        }
        return flatAdId;
    }
    
    public void removeFromCache(Long flatAdId){
      cache.delete(flatAdId);
    }
}
